package xyz.lwm.lazycat.netpipe.configure;

import xyz.lwm.lazycat.netpipe.util.Constants;
import xyz.lwm.lazycat.netpipe.util.Tokens;
import xyz.lwm.lazycat.utility.Assert;
import xyz.lwm.lazycat.utility.It;
import xyz.lwm.lazycat.utility.PathUtil;
import xyz.lwm.lazycat.utility.StringUtil;
import xyz.lwm.lazycat.web.handle.Context;
import xyz.lwm.lazycat.web.handle.Handler;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static xyz.lwm.lazycat.netpipe.util.Constants.LOGIN_PATH;
import static xyz.lwm.lazycat.utility.StrPool.STR_SLASH;

/**
 * 认证过滤器
 *
 * @author lwm
 */
public class AuthFilter implements Handler {

    private final String prefixPath;

    private final Set<String> passableUrls;

    public AuthFilter(String contextPath, List<String> passableUrls) {
        prefixPath = It.of(contextPath)
                .filter(StringUtil::isNotBlank).orElse(STR_SLASH).let(PathUtil::of)
                .let(pathable -> pathable.append(Constants.ROOT_PATH))
                .let(PathUtil.Pathable::toString).let(path -> STR_SLASH + path).get();
        this.passableUrls = It.of(passableUrls).let(HashSet::new)
                .orElse(new HashSet<>()).also(set -> set.add(LOGIN_PATH))
                .let(set -> set.stream().map(path ->
                                STR_SLASH + PathUtil.normalizePath(path))
                        .collect(Collectors.toSet())
                ).get();
    }

    @Override
    public void handle(Context ctx) {
        String path = ctx.req().getPath();
        if (path.startsWith(prefixPath) && passableUrls.contains(path.substring(prefixPath.length()))) {
            return;
        }
        String token = ctx.getHeader("Authorization");
        Assert.isTrue(StringUtil.isNotBlank(token), "请登录后再试");
        Assert.isTrue(Tokens.isValid(token), "登录已失效");
    }

}
